package com.software.car.secutiry;

import com.software.car.api.UserService;
import com.software.car.common.enums.ResultEnum;
import com.software.car.common.exception.MyException;
import com.software.car.common.utils.JwtUtil;
import com.software.car.entity.po.UserPo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description
 * @Author 魔法はまだ解けない
 * @Date 2020/10/28
 */
public class JwtRequestFilter extends OncePerRequestFilter {

    Logger logger = LoggerFactory.getLogger(getClass());

    UserService userService;

    public JwtRequestFilter(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            logger.info("\n");
            logger.info("1.用户token分析中");
            String id = request.getHeader("Authorization");
            UserPo user = null;
            if (id.equals("481fbf67e5dce3e5dc10c5a195f0e7d9b1923bca4ee448cfcbdea969d78da121")) {
                logger.info("2.用户id：1   测试用：token");
                user = userService.getUserPo("1");
            } else {
                String authorization = JwtUtil.validate(id);
                logger.info("2.用户id：" + authorization + "  信息查询中");
                user = userService.getUserPo(authorization);
            }
            // 用户授权
            Set<SimpleGrantedAuthority> authorities = getAuthorities(user);
            UsernamePasswordAuthenticationToken userAuthen = new UsernamePasswordAuthenticationToken(null, null, authorities);
            userAuthen.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(userAuthen);

            request.setAttribute("user", user);
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 通过用户及,用户组列表为用户贴通行证标签
     *
     * @param umsMember
     * @return
     */
    private Set<SimpleGrantedAuthority> getAuthorities(UserPo umsMember) {
        logger.info("3.用户权限授予中");
        Set<SimpleGrantedAuthority> authorities = new HashSet<>();
        if (umsMember == null) {
            logger.info("用户不存在！！！");
            throw new MyException(ResultEnum.EXCEPTION);
        }
        if (umsMember.getState() != 1) {
            logger.info("用户状态异常！！！");
            throw new MyException(ResultEnum.EXCEPTION);
        }
        Integer role = umsMember.getRole();
        switch (role) {
            case 1:
                authorities.add(new SimpleGrantedAuthority("ROLE_CUSTOMER"));
                break;
            case 2:
                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                break;
            case 5:
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMINISTER"));
                break;
            default:
                logger.info("用户授权失败，请通知后台人员查看数据库是否变更");
        }
        logger.info("用户权限成功！！");
        return authorities;
    }
}
